using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace GenerativeAgents.Core
{
    /// <summary>
    /// 智能体控制器
    /// 整合所有认知系统，实现完整的生成式智能体认知循环
    /// </summary>
    public class AgentController : MonoBehaviour
    {
        [Header("智能体配置")]
        [SerializeField] private string agentName = "GenerativeAgent";
        [SerializeField] private string agentPersonality = "Friendly and curious individual";
        [SerializeField] private Vector3 spawnLocation = Vector3.zero;
        [SerializeField] private float cognitiveCycleInterval = 2f; // 认知循环间隔(秒)
        
        [Header("系统启用开关")]
        [SerializeField] private bool enablePerception = true;
        [SerializeField] private bool enableMemory = true;
        [SerializeField] private bool enableReflection = true;
        [SerializeField] private bool enablePlanning = true;
        [SerializeField] private bool enableLogging = false;
        
        [Header("性能配置")]
        [SerializeField] private int maxEventsPerCycle = 10;
        [SerializeField] private float movementSpeed = 2f;
        [SerializeField] private float interactionRange = 3f;
        
        // 核心认知系统组件
        private PerceptionSystem perceptionSystem;
        private MemorySystem memorySystem;
        private RetrievalEngine retrievalEngine;
        private ReflectionSystem reflectionSystem;
        private PlanningSystem planningSystem;
        private EmbeddingEngine embeddingEngine;
        private SimpleLanguageModel languageModel;
        
        // 智能体状态
        private AgentState currentState;
        private ScratchMemory scratchMemory;
        private DateTime lastCognitiveCycle;
        private bool isCognitiveCycleRunning = false;
        
        // 当前执行状态
        private PlanItem currentPlan;
        private Vector3 targetPosition;
        private bool isMoving = false;
        private bool isInteracting = false;
        private string currentInteractionTarget;
        
        // 统计信息
        private int totalCognitiveCycles = 0;
        private int totalEventsProcessed = 0;
        private int totalReflections = 0;
        private int totalPlansCreated = 0;
        
        // 事件
        public event System.Action<AgentEvent> OnEventProcessed;
        public event System.Action<MemoryNode> OnMemoryCreated;
        public event System.Action<MemoryNode> OnReflectionGenerated;
        public event System.Action<PlanItem> OnPlanExecuted;
        public event System.Action<string> OnStateChanged;
        
        private void Awake()
        {
            InitializeAgent();
        }
        
        private void Start()
        {
            StartCognitiveCycle();
        }
        
        private void Update()
        {
            UpdateMovement();
            UpdateInteractions();
            ExecuteCurrentPlan();
        }
        
        /// <summary>
        /// 初始化智能体
        /// </summary>
        private void InitializeAgent()
        {
            try
            {
                // 初始化核心系统组件
                InitializeCognitiveSystems();
                
                // 初始化智能体状态
                InitializeAgentState();
                
                // 设置初始位置
                transform.position = spawnLocation;
                
                if (enableLogging)
                {
                    Debug.Log($"[AgentController] Agent '{agentName}' initialized successfully");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentController] Error initializing agent '{agentName}': {ex.Message}");
            }
        }
        
        /// <summary>
        /// 初始化认知系统
        /// </summary>
        private void InitializeCognitiveSystems()
        {
            // 获取或创建系统组件
            perceptionSystem = GetComponent<PerceptionSystem>() ?? gameObject.AddComponent<PerceptionSystem>();
            memorySystem = GetComponent<MemorySystem>() ?? gameObject.AddComponent<MemorySystem>();
            retrievalEngine = GetComponent<RetrievalEngine>() ?? gameObject.AddComponent<RetrievalEngine>();
            reflectionSystem = GetComponent<ReflectionSystem>() ?? gameObject.AddComponent<ReflectionSystem>();
            planningSystem = GetComponent<PlanningSystem>() ?? gameObject.AddComponent<PlanningSystem>();
            embeddingEngine = GetComponent<EmbeddingEngine>() ?? gameObject.AddComponent<EmbeddingEngine>();
            languageModel = GetComponent<SimpleLanguageModel>() ?? gameObject.AddComponent<SimpleLanguageModel>();
            
            // 设置系统间的引用关系
            SetupSystemReferences();
            
            // 订阅系统事件
            SubscribeToSystemEvents();
        }
        
        /// <summary>
        /// 设置系统间引用
        /// </summary>
        private void SetupSystemReferences()
        {
            // 设置检索引擎引用
            if (retrievalEngine != null)
            {
                retrievalEngine.Initialize(memorySystem, embeddingEngine);
            }
            
            // 设置反思系统引用
            if (reflectionSystem != null)
            {
                reflectionSystem.Initialize(memorySystem, retrievalEngine, languageModel);
            }
        }
        
        /// <summary>
        /// 订阅系统事件
        /// </summary>
        private void SubscribeToSystemEvents()
        {
            if (perceptionSystem != null)
            {
                perceptionSystem.OnEventPerceived += HandlePerceivedEvent;
            }
            
            if (reflectionSystem != null)
            {
                reflectionSystem.OnReflectionGenerated += HandleReflectionGenerated;
            }
            
            if (planningSystem != null)
            {
                planningSystem.OnPlanCreated += HandlePlanCreated;
                planningSystem.OnPlanStarted += HandlePlanStarted;
                planningSystem.OnPlanCompleted += HandlePlanCompleted;
            }
        }
        
        /// <summary>
        /// 初始化智能体状态
        /// </summary>
        private void InitializeAgentState()
        {
            // 创建基础状态
            currentState = new AgentState();
            currentState.currentLocation = transform.position;
            currentState.currentLocationName = "starting_location";
            
            // 初始化短期记忆
            scratchMemory = new ScratchMemory();
            scratchMemory.agentName = agentName;
            scratchMemory.personality = agentPersonality;
            scratchMemory.currentLocation = transform.position;
            scratchMemory.currentLocationName = currentState.currentLocationName;
            
            // 设置默认目标和习惯
            scratchMemory.goals.Add("Explore the environment");
            scratchMemory.goals.Add("Meet other agents");
            scratchMemory.goals.Add("Learn about the world");
            
            scratchMemory.habits.Add("Take breaks every hour");
            scratchMemory.habits.Add("Greet people when meeting them");
            
            lastCognitiveCycle = DateTime.Now;
        }
        
        /// <summary>
        /// 开始认知循环
        /// </summary>
        private void StartCognitiveCycle()
        {
            StartCoroutine(CognitiveCycleCoroutine());
        }
        
        /// <summary>
        /// 认知循环协程
        /// </summary>
        private IEnumerator CognitiveCycleCoroutine()
        {
            while (enabled)
            {
                if (!isCognitiveCycleRunning)
                {
                    yield return StartCoroutine(ExecuteCognitiveCycle());
                }
                
                yield return new WaitForSeconds(cognitiveCycleInterval);
            }
        }
        
        /// <summary>
        /// 执行认知循环
        /// </summary>
        private IEnumerator ExecuteCognitiveCycle()
        {
            isCognitiveCycleRunning = true;
            
            try
            {
                totalCognitiveCycles++;
                lastCognitiveCycle = DateTime.Now;
                
                if (enableLogging)
                {
                    Debug.Log($"[AgentController] Starting cognitive cycle #{totalCognitiveCycles} for {agentName}");
                }
                
                // 1. 感知阶段
                if (enablePerception)
                {
                    yield return StartCoroutine(PerceptionPhase());
                }
                
                // 2. 检索相关记忆
                yield return StartCoroutine(RetrievalPhase());
                
                // 3. 反思阶段（如果需要）
                if (enableReflection)
                {
                    yield return StartCoroutine(ReflectionPhase());
                }
                
                // 4. 计划阶段
                if (enablePlanning)
                {
                    yield return StartCoroutine(PlanningPhase());
                }
                
                // 5. 更新状态
                UpdateAgentState();
                
                if (enableLogging)
                {
                    Debug.Log($"[AgentController] Completed cognitive cycle for {agentName}");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentController] Error in cognitive cycle for {agentName}: {ex.Message}");
            }
            finally
            {
                isCognitiveCycleRunning = false;
            }
        }
        
        /// <summary>
        /// 感知阶段
        /// </summary>
        private IEnumerator PerceptionPhase()
        {
            try
            {
                if (perceptionSystem != null)
                {
                    // 执行感知循环
                    var perceivedEvents = perceptionSystem.PerformPerceptionCycle();
                    
                    // 限制事件数量以避免过载
                    if (perceivedEvents.Count > maxEventsPerCycle)
                    {
                        perceivedEvents = perceivedEvents.Take(maxEventsPerCycle).ToList();
                    }
                    
                    // 处理感知到的事件
                    foreach (var agentEvent in perceivedEvents)
                    {
                        ProcessPerceivedEvent(agentEvent);
                        totalEventsProcessed++;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentController] Error in perception phase: {ex.Message}");
            }
            
            yield return null;
        }
        
        /// <summary>
        /// 检索阶段
        /// </summary>
        private IEnumerator RetrievalPhase()
        {
            try
            {
                if (retrievalEngine != null && !string.IsNullOrEmpty(currentState.currentAction))
                {
                    // 基于当前行动检索相关记忆
                    var query = MemoryQuery.CreateTextQuery(currentState.currentAction, 5);
                    query.agentName = agentName;
                    query.currentLocation = transform.position;
                    
                    var relevantMemories = retrievalEngine.Retrieve(query);
                    
                    // 更新短期记忆中的相关记忆
                    scratchMemory.relevantMemories = relevantMemories;
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentController] Error in retrieval phase: {ex.Message}");
            }
            
            yield return null;
        }
        
        /// <summary>
        /// 反思阶段
        /// </summary>
        private IEnumerator ReflectionPhase()
        {
            try
            {
                if (reflectionSystem != null && reflectionSystem.ShouldReflect(scratchMemory))
                {
                    reflectionSystem.PerformReflection(scratchMemory);
                    totalReflections++;
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentController] Error in reflection phase: {ex.Message}");
            }
            
            yield return null;
        }
        
        /// <summary>
        /// 计划阶段
        /// </summary>
        private IEnumerator PlanningPhase()
        {
            try
            {
                if (planningSystem != null)
                {
                    // 检查是否需要重新计划
                    bool needsReplanning = currentState.needsReplanning || 
                                         currentPlan == null || 
                                         currentPlan.status == PlanStatus.Completed ||
                                         currentPlan.status == PlanStatus.Cancelled;
                    
                    if (needsReplanning)
                    {
                        planningSystem.TriggerReplanning("cognitive_cycle", scratchMemory);
                        currentState.needsReplanning = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentController] Error in planning phase: {ex.Message}");
            }
            
            yield return null;
        }
        
        /// <summary>
        /// 处理感知到的事件
        /// </summary>
        private void ProcessPerceivedEvent(AgentEvent agentEvent)
        {
            try
            {
                // 存储到记忆系统
                if (enableMemory && memorySystem != null)
                {
                    var memoryNode = memorySystem.StoreEvent(agentEvent);
                    OnMemoryCreated?.Invoke(memoryNode);
                }
                
                // 更新重要性触发器
                currentState.importanceTriggerCurrent -= agentEvent.poignancy;
                
                // 更新短期记忆
                UpdateScratchMemoryWithEvent(agentEvent);
                
                OnEventProcessed?.Invoke(agentEvent);
                
                if (enableLogging)
                {
                    Debug.Log($"[AgentController] Processed event: {agentEvent.description}");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentController] Error processing perceived event: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 更新短期记忆
        /// </summary>
        private void UpdateScratchMemoryWithEvent(AgentEvent agentEvent)
        {
            // 更新对话伙伴
            if (agentEvent.type == EventType.Conversation && !string.IsNullOrEmpty(agentEvent.subject))
            {
                if (!scratchMemory.recentConversationPartners.Contains(agentEvent.subject))
                {
                    scratchMemory.recentConversationPartners.Add(agentEvent.subject);
                    
                    // 限制列表大小
                    if (scratchMemory.recentConversationPartners.Count > 10)
                    {
                        scratchMemory.recentConversationPartners.RemoveAt(0);
                    }
                }
                
                // 更新社交电池
                scratchMemory.socialBattery = Mathf.Min(1f, scratchMemory.socialBattery + 0.1f);
            }
            
            // 更新位置信息
            scratchMemory.currentLocation = transform.position;
            
            // 更新最后活动时间
            scratchMemory.lastActivityTime = DateTime.Now;
        }
        
        /// <summary>
        /// 更新移动
        /// </summary>
        private void UpdateMovement()
        {
            if (isMoving && targetPosition != Vector3.zero)
            {
                var direction = (targetPosition - transform.position).normalized;
                var distance = Vector3.Distance(transform.position, targetPosition);
                
                if (distance < 0.5f)
                {
                    // 到达目标
                    transform.position = targetPosition;
                    isMoving = false;
                    targetPosition = Vector3.zero;
                    
                    // 更新状态
                    currentState.currentLocation = transform.position;
                    scratchMemory.currentLocation = transform.position;
                    
                    OnStateChanged?.Invoke("arrived_at_destination");
                }
                else
                {
                    // 继续移动
                    transform.position += direction * movementSpeed * Time.deltaTime;
                }
            }
        }
        
        /// <summary>
        /// 更新交互
        /// </summary>
        private void UpdateInteractions()
        {
            if (isInteracting && !string.IsNullOrEmpty(currentInteractionTarget))
            {
                // 简化的交互逻辑
                // 实际实现中应该处理具体的交互行为
            }
        }
        
        /// <summary>
        /// 执行当前计划
        /// </summary>
        private void ExecuteCurrentPlan()
        {
            if (currentPlan != null && currentPlan.status == PlanStatus.InProgress)
            {
                // 根据计划类型执行相应行动
                ExecutePlanAction(currentPlan);
            }
        }
        
        /// <summary>
        /// 执行计划行动
        /// </summary>
        private void ExecutePlanAction(PlanItem plan)
        {
            try
            {
                switch (plan.action)
                {
                    case "move":
                    case "go_to":
                        if (!isMoving)
                        {
                            MoveTo(plan.targetLocation);
                        }
                        break;
                        
                    case "interact":
                    case "social_interaction":
                        if (!isInteracting && plan.involvedAgents.Count > 0)
                        {
                            StartInteraction(plan.involvedAgents[0]);
                        }
                        break;
                        
                    case "wait":
                    case "idle":
                        // 等待行动
                        break;
                        
                    case "explore":
                        if (!isMoving)
                        {
                            // 随机探索
                            var randomDirection = UnityEngine.Random.insideUnitSphere * 10f;
                            randomDirection.y = 0;
                            MoveTo(transform.position + randomDirection);
                        }
                        break;
                        
                    default:
                        if (enableLogging)
                        {
                            Debug.Log($"[AgentController] Unknown action: {plan.action}");
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentController] Error executing plan action: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 移动到目标位置
        /// </summary>
        public void MoveTo(Vector3 target)
        {
            targetPosition = target;
            isMoving = true;
            currentState.currentAction = "moving";
            
            OnStateChanged?.Invoke("started_moving");
        }
        
        /// <summary>
        /// 开始交互
        /// </summary>
        public void StartInteraction(string targetAgent)
        {
            currentInteractionTarget = targetAgent;
            isInteracting = true;
            currentState.isInConversation = true;
            currentState.conversationPartner = targetAgent;
            currentState.currentAction = "interacting";
            
            OnStateChanged?.Invoke("started_interaction");
        }
        
        /// <summary>
        /// 结束交互
        /// </summary>
        public void EndInteraction()
        {
            currentInteractionTarget = null;
            isInteracting = false;
            currentState.isInConversation = false;
            currentState.conversationPartner = null;
            currentState.currentAction = "idle";
            
            OnStateChanged?.Invoke("ended_interaction");
        }
        
        /// <summary>
        /// 更新智能体状态
        /// </summary>
        private void UpdateAgentState()
        {
            try
            {
                // 更新基础状态
                currentState.currentLocation = transform.position;
                currentState.lastPlanUpdate = DateTime.Now;
                
                // 更新能量等级（简化模拟）
                var timeSinceLastCycle = (DateTime.Now - lastCognitiveCycle).TotalMinutes;
                currentState.energy = Mathf.Max(0.1f, currentState.energy - (float)(timeSinceLastCycle * 0.01f));
                
                // 更新心情（基于最近事件）
                UpdateMood();
                
                // 更新短期记忆
                scratchMemory.lastActivityTime = DateTime.Now;
                scratchMemory.currentLocation = transform.position;
                scratchMemory.agentName = agentName;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentController] Error updating agent state: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 更新心情
        /// </summary>
        private void UpdateMood()
        {
            // 简化的心情更新逻辑
            var recentImportantEvents = memorySystem?.AssociativeMemory?.GetRecentMemories(TimeSpan.FromMinutes(30), 5)
                ?.Where(m => m.poignancy >= 6).Count() ?? 0;
            
            if (recentImportantEvents > 3)
            {
                currentState.mood = "excited";
            }
            else if (recentImportantEvents > 1)
            {
                currentState.mood = "content";
            }
            else if (currentState.energy < 0.3f)
            {
                currentState.mood = "tired";
            }
            else
            {
                currentState.mood = "neutral";
            }
        }
        
        // 事件处理器
        private void HandlePerceivedEvent(AgentEvent agentEvent)
        {
            // 事件已在ProcessPerceivedEvent中处理
        }
        
        private void HandleReflectionGenerated(MemoryNode reflection)
        {
            OnReflectionGenerated?.Invoke(reflection);
            
            if (enableLogging)
            {
                Debug.Log($"[AgentController] Generated reflection: {reflection.description}");
            }
        }
        
        private void HandlePlanCreated(PlanItem plan)
        {
            totalPlansCreated++;
            
            if (enableLogging)
            {
                Debug.Log($"[AgentController] Created plan: {plan.description}");
            }
        }
        
        private void HandlePlanStarted(PlanItem plan)
        {
            currentPlan = plan;
            currentState.currentPlanId = plan.planId;
            OnPlanExecuted?.Invoke(plan);
            
            if (enableLogging)
            {
                Debug.Log($"[AgentController] Started executing plan: {plan.description}");
            }
        }
        
        private void HandlePlanCompleted(PlanItem plan)
        {
            if (currentPlan?.planId == plan.planId)
            {
                currentPlan = null;
                currentState.currentPlanId = null;
                currentState.needsReplanning = true;
            }
            
            if (enableLogging)
            {
                Debug.Log($"[AgentController] Completed plan: {plan.description}");
            }
        }
        
        /// <summary>
        /// 获取智能体状态
        /// </summary>
        public AgentState GetAgentState()
        {
            return currentState;
        }
        
        /// <summary>
        /// 获取短期记忆
        /// </summary>
        public ScratchMemory GetScratchMemory()
        {
            return scratchMemory;
        }
        
        /// <summary>
        /// 获取当前计划
        /// </summary>
        public PlanItem GetCurrentPlan()
        {
            return currentPlan;
        }
        
        /// <summary>
        /// 手动触发认知循环
        /// </summary>
        public void TriggerCognitiveCycle()
        {
            if (!isCognitiveCycleRunning)
            {
                StartCoroutine(ExecuteCognitiveCycle());
            }
        }
        
        /// <summary>
        /// 获取统计信息
        /// </summary>
        public string GetAgentStats()
        {
            var stats = $"Agent: {agentName}\n";
            stats += $"Cognitive Cycles: {totalCognitiveCycles}\n";
            stats += $"Events Processed: {totalEventsProcessed}\n";
            stats += $"Reflections: {totalReflections}\n";
            stats += $"Plans Created: {totalPlansCreated}\n";
            stats += $"Current Action: {currentState.currentAction}\n";
            stats += $"Mood: {currentState.mood}\n";
            stats += $"Energy: {currentState.energy:F2}\n";
            stats += $"Location: {transform.position}\n";
            
            if (memorySystem != null)
            {
                stats += $"Memories: {memorySystem.AssociativeMemory.GetMemoryCount()}\n";
            }
            
            return stats;
        }
        
        /// <summary>
        /// 设置智能体配置
        /// </summary>
        public void SetAgentConfiguration(string name, string personality, Vector3 spawn)
        {
            agentName = name;
            agentPersonality = personality;
            spawnLocation = spawn;
            
            if (scratchMemory != null)
            {
                scratchMemory.agentName = name;
                scratchMemory.personality = personality;
            }
        }
        
        /// <summary>
        /// 暂停/恢复认知循环
        /// </summary>
        public void SetCognitiveCyclePaused(bool paused)
        {
            enabled = !paused;
        }
        
        /// <summary>
        /// 重置智能体状态
        /// </summary>
        public void ResetAgent()
        {
            // 重置状态
            currentState = new AgentState();
            InitializeAgentState();
            
            // 重置位置
            transform.position = spawnLocation;
            
            // 重置移动和交互状态
            isMoving = false;
            isInteracting = false;
            currentPlan = null;
            targetPosition = Vector3.zero;
            currentInteractionTarget = null;
            
            // 重置统计
            totalCognitiveCycles = 0;
            totalEventsProcessed = 0;
            totalReflections = 0;
            totalPlansCreated = 0;
            
            if (enableLogging)
            {
                Debug.Log($"[AgentController] Agent '{agentName}' has been reset");
            }
        }
        
        private void OnDestroy()
        {
            // 取消订阅事件
            if (perceptionSystem != null)
            {
                perceptionSystem.OnEventPerceived -= HandlePerceivedEvent;
            }
            
            if (reflectionSystem != null)
            {
                reflectionSystem.OnReflectionGenerated -= HandleReflectionGenerated;
            }
            
            if (planningSystem != null)
            {
                planningSystem.OnPlanCreated -= HandlePlanCreated;
                planningSystem.OnPlanStarted -= HandlePlanStarted;
                planningSystem.OnPlanCompleted -= HandlePlanCompleted;
            }
        }
    }
}